package com.shen.server;

import com.shen.user.User;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Author:shen
 * CreateDate:2020/6/9.
 * Function:
 */
public class TCPServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket accept=null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        UserService userService=null;

        try {
            serverSocket=new ServerSocket(3333);
            while (true){
                accept = serverSocket.accept();//接收客户端的信息
                //获得传输过来的对象信息
                 inputStream = accept.getInputStream();
                ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
                User user = (User) objectInputStream.readObject();
                System.out.println(user);
                userService=new UserService();
                boolean flag = userService.checkUser(user);
                System.out.println(flag);
                String msg="";
                if(flag==true){
                    msg="登录成功！";
                }else{
                    msg="登录失败！";
                }
                outputStream = accept.getOutputStream();
                outputStream.write(msg.getBytes());
                accept.shutdownOutput();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
